package server;

import java.io.*;
import java.net.URL;

/**
 * @program: stage_2_module_1
 * @description:
 * @author: zhangxiaoyang
 * @date: 2020/8/4 5:15 下午
 **/
public class DiskClassLoader extends ClassLoader {

    private String myLibPath;

    public DiskClassLoader(String myLibPath) {
        this.myLibPath = myLibPath;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String filename = getFileName(name);

        File file = new File(myLibPath, filename);
        try (FileInputStream is = new FileInputStream(file);
             ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            int len = 0;
            while ((len = is.read()) != -1) {
                bos.write(len);
            }
            byte[] data = bos.toByteArray();
            return defineClass(name.replaceAll("/","\\."), data, 0, data.length);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return super.findClass(name);
    }

    private String getFileName(String name) {
        int index = name.lastIndexOf('.');
        if (index == -1) {
            return name + ".class";
        } else {
            return name.substring(index + 1) + ".class";
        }
    }

    @Override
    public URL getResource(String name) {
        return super.getResource(myLibPath + name);
    }
}
